<template>
    <div class="console-page" v-loading="loading" element-loading-delay="200">
        <el-form inline :model="searchForm" class="e-page form-item" spellcheck="false" @submit.native.prevent>
            <el-row class="toolbar">
                <el-col :span="16" style="padding-right: 5px">
                    <el-button @click="getData" circle :icon="getIcon('refresh')" class="button-auto-resize" />
                </el-col>
                <el-col :span="8" style="text-align: right">
                    <el-button circle :icon="getIcon('plus')" class="button-auto-resize" @click="addBucket" />
                </el-col>
            </el-row>
        </el-form>
        <el-row class="tag-list">
            <el-scrollbar class="full-percent" ref="scrollbarRef">
                <div v-if="tag.length === 0">
                    <div class="empty">
                        暂无数据
                    </div>
                </div>
                <div v-else>
                    <div v-waterfall.padding>
                        <el-card v-for="(item, index) in tag" :key="index">
                            <template #header>
                                <div class="e-page card-header" onselectstart="return false">
                                    <el-row>
                                        <el-col :span="16">
                                            <div>{{ index + 1 }}. {{ item.name }}</div>
                                        </el-col>
                                        <el-col :span="8" style="text-align: right;">
                                            <el-button link :icon="getIcon('delete')" @click="deleteBucket(item.name)"
                                                :confirmTitle="`确定删除桶「${item.name}」?`" />
                                            <el-button link :icon="getIcon('view')"
                                                @click="showFilesDrawer(item.name)" />
                                            <el-button link :icon="getIcon('UploadFilled')"
                                                @click="showUploadDrawer(item.name)" />
                                        </el-col>
                                    </el-row>
                                </div>
                            </template>
                            <el-row class="bucket-item">
                                <el-col :span="6" class="bucket-label"
                                    style="text-align: right;padding-right: 10px;">创建时间:</el-col>
                                <el-col :span="18" class="bucket-info">{{
                                    new Date(parseInt(item.creationDate)).format("YYYY-MM-DD HH:mm:ss")
                                }}
                                </el-col>
                            </el-row>
                            <el-row class="bucket-item">
                                <el-col :span="6" class="bucket-label"
                                    style="text-align: right;padding-right: 10px">占用空间:</el-col>
                                <el-col :span="18" class="bucket-info">{{
                                    item.hasOwnProperty("size") ? formatSize(item.size) : 0
                                }}
                                </el-col>
                            </el-row>
                            <el-row class="bucket-item">
                                <el-col :span="6" class="bucket-label"
                                    style="text-align: right;padding-right: 10px">已有文件:</el-col>
                                <el-col :span="18" class="bucket-info">{{
                                    item.hasOwnProperty("files") ? item.files : 0
                                }}
                                </el-col>
                            </el-row>
                        </el-card>
                    </div>
                </div>
            </el-scrollbar>
        </el-row>
        <el-drawer v-model="showUpload" direction="rtl" :show-close="false" @open="openUpload" append-to-body
            :before-close="beforeCloseUpload" :close-on-press-escape="false" size="830px" @closed="closeUpload"
            @close="getData" class="minio-dialog">
            <minioUpload :bucket="bucket" ref="uploadRef" />
        </el-drawer>
        <el-drawer v-model="showFile" direction="ltr" :show-close="false" @open="openFiles" @close="getData"
            :close-on-press-escape="false" size="80%" @closed="closeFiles" destroy-on-close append-to-body
            class="minio-dialog">
            <files :bucket="bucket" ref="filesRef" :tags="tag" />
        </el-drawer>
        <el-dialog title="添加桶" v-model="showBucketDialog" width="700px" @closed="closeBucketDialog"
            :close-on-click-modal="false" class="minio-dialog" :show-close="false" top="25vh" @open="open"
            append-to-body>
            <el-row>
                <el-col :span="4" class="new-bucket-name font-auto-resize">桶名称</el-col>
                <el-col :span="20">
                    <el-input class="input-auto-resize" v-model="newBucket.name" @keydown.enter.native="createBucket"
                        ref="bucketRef" />
                </el-col>
            </el-row>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showBucketDialog = false" class="fit-auto-resize">取 消</el-button>
                    <el-button @click="createBucket" type="primary" class="fit-auto-resize">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { formatSize, getIcon } from "@/utils/tools"
import { ElMessageBox } from "element-plus"
import { useElMessage, useModalSize, useRequest } from "@usehook"

let tag = $ref([])
let bucket = $ref("")
let showUpload = $ref(false)
let showFile = $ref(false)
let searchForm = $ref({ name: "", value: "", classCode: "" })
let showBucketDialog = $ref(false)
let newBucket = $ref({ name: "" })
let bucketRef = $ref(null)
let loading = $ref(false)
const uploadRef = $ref(null)

const isValidName = (name) => {
    // const regex = /^(?=.*[a-z0-9._-]{3,20}$)(?!0{1,3}(?:\.[0-9]{1,3}){3}$)(?!_)(?![-.]*_)(?!.*,)[a-z0-9._-]{1,20}$/;
    const regex = /^[a-zA-Z][a-zA-Z0-9\s-]*$/
    return regex.test(name);
}

const createBucket = () => {
    if (!isValidName(newBucket.name)) {
        useElMessage.error({
            // message: "<div style='text-align: center;font-size: 16px'>桶名称不符合要求</div><br/>名称的长度介于 3 和 20 个字符之间，并且只能包含小写字母、数字、句点和短划线。<br/>" +
            //     "名称中的每个标签必须以小写字母或数字开头。<br/>" +
            //     "名称不能包含下划线、以短划线结束、包含连续句点或在句点旁边使用短划线。",
            message: "<div style='text-align: center;font-size: 15px'>桶名称不符合要求</div><div style='padding-top: 8px'>必须以字母开头，可以包含数字或-符号</div>",
            dangerouslyUseHTMLString: true,
            center: true,
            duration: 5000
        })
        return
    }
    useRequest({ url: "/file/tag", tag: newBucket.name, method: "post" }).then(e => {
        if (e.status) {
            useElMessage("桶[" + newBucket.name + "]创建成功")
            getData()
            closeBucketDialog()
        } else {
            if (e.message) useElMessage.error(e.message)
        }
    })
}

const deleteBucket = (bucket) => {
    useRequest({ url: "/file/delTag", tag: bucket, method: "post" }).then(e => {
        if (e.status) {
            useElMessage("桶删除成功")
            getData()
        } else {
            if (e.message) useElMessage.error(e.message)
        }
    })
}

const changePolicy = (item) => {
    useRequest({ url: "/file/policy", tag: item.name, policy: item.policy, method: "post" }).then(e => {
        if (e.status) {
            useElMessage("权限修改成功[" + e.message + "]")
        } else {
            useElMessage.error("权限修改失败")
        }
    })
}

const open = () => {
    nextTick(() => {
        bucketRef.focus()
    })
}

const closeBucketDialog = () => {
    showBucketDialog = false
    useModalSize(false)
    newBucket = { name: "", policy: "禁止访问" }
}


const addBucket = () => {
    showBucketDialog = true
    useModalSize()
}
const showUploadDrawer = (_bucket) => {
    // let link = document.createElement('a')
    // const random = randomKey(24)
    // const key = encrypt(JSON.stringify({'bucket': bucket, 'token': getToken()}), random)
    // link.href = 'http://minio.dansj.cn?d=' + encodeURI(encodeURIComponent(key + random))
    // link.target = 'openMinioUpload'
    // link.click()
    // link.remove()
    showUpload = true
    useModalSize()
    bucket = _bucket
}
const showFilesDrawer = (_bucket) => {
    showFile = true
    useModalSize()
    bucket = _bucket
}
const openUpload = () => {
    nextTick(() => {
        // uploadRef.checkFileHandler()
    })
}
const beforeCloseUpload = (done) => {
    if (uploadRef.checkUploadComplete()) {
        uploadRef.clearFileHandler()
        done()
    } else {
        ElMessageBox.confirm('关闭后将清空文件列表和上传任务, 确定关闭?', '提示', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: ' ',
            cancelButtonText: ' ',
            type: 'warning',
            customClass: "c-dialog forbid-select",
            closeOnClickModal: false,
            cancelButtonClass: "iconfont icon-close button-auto-resize",
            confirmButtonClass: 'iconfont icon-check button-auto-resize',
            roundButton: true,
            showClose: false,
        }).then(() => {
            uploadRef.clearFileHandler()
            uploadRef.abortUploadRequest()
            done()
        }).catch(_ => {
        }).finally(() => {
        })
    }
}
const closeUpload = () => {
    showUpload = false
    useModalSize(false)
    bucket = ""
}
const openFiles = () => {

}
const closeFiles = () => {
    showFile = false
    useModalSize(false)
    bucket = ""
}
const getData = () => {
    loading = true
    useRequest({ url: "/file/tag" }).then(resp => {
        if (resp && resp.status) {
            resp.data.sort((a, b) => {
                return a.creationDate - b.creationDate
            })
            tag = resp.data
        }
    }).finally(() => {
        loading = false
    })
}

onMounted(() => {
    getData()
})
</script>

<style scoped>
:deep(.el-form-item__label) {
    text-align: left;
    padding-left: 10px;
    font-size: var(--font-size);
    padding-top: 14px;
    font-size: var(--font-size);
}

:deep(.el-card__body .el-form-item) {
    height: 35px;
}

:deep(.el-scrollbar__wrap) {
    overflow-x: hidden;
}

:deep(.el-form-item__error) {
    padding-top: 1px;
}

:deep(.el-scrollbar__bar.is-vertical) {
    width: 0;
}

:deep(.bucket-info .el-radio__label) {
    font-size: var(--font-size) !important;
    padding-left: 5px !important;
}

:deep(.bucket-info .el-radio) {
    margin-right: 6px;
}

:deep(.bucket-info .el-radio__inner) {
    width: 10px;
    height: 10px;
}

/*错误提示信息位置*/
:deep(.el-form .el-form-item__error) {
    top: 34%;
    right: 3%;
    left: unset;
}

:deep(.el-form-item__error) {
    padding-top: 1px;
}

:deep(.el-card__header) {
    padding: 10px 15px;
}

:deep(.el-card__body) {
    padding: 10px 15px;
}

:deep(.bucket-info) {
    height: calc(var(--font-size) * 2);
    line-height: 18px;
    max-width: calc(100% - var(--font-size) * 5);
    display: flex;
    align-items: center;
}

:deep(.bucket-label) {
    min-width: calc(var(--font-size) * 5);
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

:deep(.el-select .el-input) {
    width: 70px;
}

:deep(.el-input-group__append) {
    background: #fff;
}

:deep(.tag-list) {
    height: calc(100% - var(--font-size)* 2 - 11px);
}

:deep(.empty) {
    width: 50%;
    display: block;
    margin: 10% auto 0 auto;
    text-align: center
}

:deep(.card-header) {
    font-size: calc(var(--font-size) + 3px);
    white-space: nowrap;
    position: relative
}

:deep(.bucket-item) {
    height: calc(var(--font-size) * 2);
}

:deep(.new-bucket-name) {
    padding-right: 10px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
</style>

<style>
.close-upload .el-message-box__message p {
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: var(--font-size);
}

.minio-dialog .el-drawer__header {
    margin-bottom: 0 !important;
    padding: 5px 5px 0;
}

.minio-dialog .el-drawer__body {
    padding: 5px;
}

.minio-dialog .el-drawer__body {
    overflow: hidden;
}

.minio-dialog .el-dialog__body {
    padding: 10px;
}

.minio-dialog .el-dialog__footer {
    padding: 10px;
}
</style>